package org.ioriframework.boot.config;

import org.ioriframework.boot.sso.support.filter.SsoFilter;
import org.ioriframework.boot.web.support.filter.InitAttributesFilter;
import org.ioriframework.boot.web.support.filter.ResourceFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CorsFilter;

/**
 * 过滤器相关配置
 * PS. 通过FilterRegistrationBean来进行注册过滤器，setOrder可以指定执行顺序，如果不指定，注册方法的顺序直接影响过滤器的执行顺序
 * @author iori
 *
 */
@Configuration
public class FilterConfig {
	
	private static Logger log = LoggerFactory.getLogger(FilterConfig.class);

	/**
	 * 注册请求初始化过滤器
	 * @return
	 */
	@Bean
	public FilterRegistrationBean<InitAttributesFilter> initAttributesFilterRegistration() {
		log.info("Registing initAttributesFilter.....");
		FilterRegistrationBean<InitAttributesFilter> bean = new FilterRegistrationBean<>();
		bean.setName("initAttributesFilter");
		bean.setFilter(new InitAttributesFilter());
		bean.setOrder(FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - 20);
		bean.addUrlPatterns("/*");
		return bean;
	}
	

	/**
	 * 注册SSO过滤器
	 * @return
	 */
	@Bean
	public FilterRegistrationBean<SsoFilter> ssoFilterRegistration() {
		log.info("Registing ssoFilterRegistration.....");
		FilterRegistrationBean<SsoFilter> bean = new FilterRegistrationBean<>();
		bean.setName("ssoFilter");
		bean.setFilter(new SsoFilter());
		bean.setOrder(FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - 15);
		bean.addUrlPatterns("/*");
		bean.addInitParameter("appName", "iori");
		// intra：内网，inter：外网
		bean.addInitParameter("serverScope", "intra");
		bean.addInitParameter("exclusions", "*.js,*.css,*.class,*.properties,*.jpg,*.gif,*.bmp,*.woff,*.map");
		// 检测到用户未登录时，是否跳转到登录页面,默认为false不跳转
		bean.addInitParameter("isRedirect", "true");
		return bean;
	}

	/**
	 * 注册协助加载资源的过滤器
	 * @return
	 */
	@Bean
	public FilterRegistrationBean<ResourceFilter> resourceFilterRegistration() {
		log.info("Registing resourceFilter.....");
		FilterRegistrationBean<ResourceFilter> bean = new FilterRegistrationBean<>();
		bean.setName("resourceFilter");
		bean.setFilter(new ResourceFilter());
		bean.setOrder(FilterRegistrationBean.REQUEST_WRAPPER_FILTER_MAX_ORDER - 10);
		bean.addUrlPatterns("/*");
		return bean;
	}
	
	/**
	 * 注册跨域访问策略的过滤器
	 * @return
	 */
	@Bean
	public FilterRegistrationBean<CorsFilter> ioriCrosFilterRegistration(CorsFilter ioriCorsFilter) {
		log.info("Registing ioriCrosFilter.....");
		FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>();
		bean.setName("ioriCrosFilter");
		bean.setFilter(ioriCorsFilter);
		bean.setOrder(Integer.MIN_VALUE);
		bean.addUrlPatterns("/*");
		return bean;
	}
	
}
